package com.hdy.javachatroomdemo.Config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Service
@Slf4j
public class LocalFileService {
    
    @Value("${file.local.storage.path:./uploads}")
    private String storagePath;
    
    @Value("${file.local.download.url:http://localhost:8080/file/local}")
    private String downloadUrl;
    
    /**
     * 上传文件到本地存储
     */
    public String uploadFile(MultipartFile file) throws IOException {
        // 确保存储目录存在
        Path storageDir = Paths.get(storagePath);
        if (!Files.exists(storageDir)) {
            Files.createDirectories(storageDir);
        }
        
        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String extension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        String fileName = UUID.randomUUID().toString() + extension;
        
        // 保存文件
        Path filePath = storageDir.resolve(fileName);
        Files.copy(file.getInputStream(), filePath);
        
        log.info("文件已保存到本地: {}", filePath);
        
        return fileName;
    }
    
    /**
     * 获取文件路径
     */
    public Path getFilePath(String fileName) {
        return Paths.get(storagePath, fileName);
    }
    
    /**
     * 检查文件是否存在
     */
    public boolean fileExists(String fileName) {
        return Files.exists(getFilePath(fileName));
    }
    
    /**
     * 获取下载URL
     */
    public String getDownloadUrl(String fileName) {
        return downloadUrl + "/" + fileName;
    }
    
    /**
     * 删除文件
     */
    public boolean deleteFile(String fileName) {
        try {
            Path filePath = getFilePath(fileName);
            return Files.deleteIfExists(filePath);
        } catch (IOException e) {
            log.error("删除文件失败: {}", fileName, e);
            return false;
        }
    }
} 